﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Looptribe.Moodlin8.Model;
using Looptribe.WinRT.Toolkit;

namespace Looptribe.Moodlin8.ViewModel
{
    public class CourseEventsViewModel : LoadingViewModel
    {
        private Course _course;
        public Course Course
        {
            get { return _course; }
            set { Set(() => Course, ref _course, value); }
        }

        private readonly ObservableCollection<EventWrapper> _events = new ObservableCollection<EventWrapper>();
        public ObservableCollection<EventWrapper> Events { get { return _events; } }

        public async Task LoadContent(Course course)
        {
            Course = course;
            await Refresh();
        }

        public async override Task Refresh()
        {
            Events.Clear();

            IsLoading = true;
            var events = (await Api.GetEventsAsync(DateTime.Now, DateTime.Now.AddMonths(2))).Data;
            IsLoading = false;

            if (events != null)
                Events.AddMany(events.Where(a => a.CourseId == Course.Id).OrderBy(a => a.TimeStart).Select(a => new EventWrapper(a)));
        }
    }
}
